package com.msb.dongbao.portal.web.controller.studyCaptcha;

import com.msb.dongbao.portal.web.util.JCaptchaUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author: mayu
 * @date: 2021年05月28日 14:55
 */
@RestController
@RequestMapping("/jcaptcha")
public class JCaptchaController {

    @GetMapping("/generator")
    public void generatorCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getSession().getId();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            BufferedImage bufferedImage = JCaptchaUtil.getService().getImageChallengeForID(id);

            //JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(byteArrayOutputStream);
            //jpegEncoder.encode(bufferedImage);

            //以这个代替掉 JPEGCodec，解决maven打包：程序包com.sun.image.codec.jpeg不存在问题
            ImageIO.write(bufferedImage, "jpeg", byteArrayOutputStream);

            response.setHeader("Cache-Control", "no-store");
            response.setContentType("image/jpeg");

            byte[] bytes = byteArrayOutputStream.toByteArray();
            ServletOutputStream servletOutputStream = response.getOutputStream();

            servletOutputStream.write(bytes);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/verify")
    public String verify(String verifyCode, HttpServletRequest request) {
        Boolean aBoolean = JCaptchaUtil.getService().validateResponseForID(request.getSession().getId(), verifyCode);
        if (aBoolean) {
            return "通过";
        }
        return "不通过";
    }
}
